<template>
  <px-dialog v-model="visible" width="80%" @close="closeDialog">
    <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" inline label-width="90px">
      <px-form-item label="设备名称">
        <px-input v-model="queryParams.value" placeholder="请输入设备名称/设备编号" clearable @keyup.enter="queryTable" />
      </px-form-item>
      <px-form-item label="厂区">
        <px-select v-model="queryParams.facCode" placeholder="请选择厂区" clearable filterable @change="handleChangeFac">
          <px-option v-for="item in facList" :key="item.id" :label="item.name" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="科室">
        <px-select v-model="queryParams.className" placeholder="请选择科室" clearable filterable @change="handleChangeClass">
          <px-option v-for="item in classNameList" :key="item.id" :label="item.name" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="系统">
        <px-tree-select
          v-model="queryParams.systemCodes"
          clearable
          style="width: 100%"
          placeholder="请选择设备系统（树状图）"
          :props="defaultProps"
          :data="systemList"
          check-strictly
          :render-after-expand="false"
          @clear="handleSystemClear"
          @node-click="nodeClick"
          @focus="handleSystemFocus"
        />
      </px-form-item>
      <px-form-item label="设备总称">
        <px-select v-model="queryParams.categoryId" placeholder="请选择设备总称" clearable filterable @change="handleCategoryChange">
          <px-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
        </px-select>
      </px-form-item>
      <px-form-item label="设备类型">
        <px-select-v2
          v-model="queryParams.typeId"
          filterable
          :options="typeIdList"
          placeholder="请选择设备类型"
          @focus="handleTypeFocus"
          @change="handleTypeChange"
        />
      </px-form-item>
      <px-form-item label="设备型号">
        <px-select-v2 v-model="queryParams.modelId" filterable :options="modelIdList" placeholder="请选择设备型号" @focus="handleModelFocus" />
      </px-form-item>

      <px-form-item label="设备位置" prop="positionCodes">
        <px-cascader
          ref="cascaderRef"
          v-model="queryParams.positionCodes"
          filterable
          clearable
          :options="positionList"
          :props="cascaderefaultProps"
          placeholder="请选择设备位置"
          @change="cascaderRef.togglePopperVisible()"
        />
      </px-form-item>

      <px-form-item>
        <px-button type="primary" @click="queryTable">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
      </px-form-item>
    </px-form>

    <px-table v-loading="loading" :data="equipTypeList" height="calc(100vh - 500px)" border @selection-change="handleSelectionChange">
      <px-table-column type="selection" width="55" align="center" />
      <px-table-column label="序号" type="index" width="55" align="center" fixed="left" />
      <px-table-column min-width="180" show-overflow-tooltip label="设备编号" align="center" fixed="left" prop="eqpId" />
      <px-table-column min-width="150" show-overflow-tooltip label="设备名称" align="center" prop="eqpName" />
      <px-table-column min-width="120" show-overflow-tooltip label="厂区" align="center" prop="facName" />
      <px-table-column min-width="80" show-overflow-tooltip label="科室" align="center" prop="classNameDesc" />
      <px-table-column min-width="150" show-overflow-tooltip label="系统" align="center" prop="systemName" />
      <px-table-column min-width="120" show-overflow-tooltip label="设备总称" prop="categoryName" />
      <px-table-column min-width="120" show-overflow-tooltip label="设备类型" prop="typeName" />
      <px-table-column min-width="120" show-overflow-tooltip label="设备型号" prop="modelName" />
      <px-table-column width="100" show-overflow-tooltip label="设备状态" align="center" prop="eqpStatusValue">
        <template #default="scope">
          <px-tag
            effect="plain"
            :style="{
              color: `${tagBorderColorList[scope.row.eqpStatus]}`,
              border: `1px solid ${tagBorderColorList[scope.row.eqpStatus]}`,
              backgroundColor: `${tagBgColorList[scope.row.eqpStatus]}`
            }"
          >
            {{ scope.row.eqpStatusValue }}
          </px-tag>
        </template>
      </px-table-column>
    </px-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="queryTable" />

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="closeDialog">取消</px-button>
        <px-button type="primary" @click="confirm()">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup lang="ts">
import { queryCurrentClassList, queryDictData } from "@/api/common";
import { getEquipModelSelect, getEquipNameSelect, getEquipTypeSelect, queryEquipLedger, querySystemSelect } from "@/api/equip/archive";

import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { getTableData } from "@/api/system/positionManage";
const cascaderRef = ref();
const cascaderefaultProps = {
  children: "children",
  label: "name",
  value: "code",
  checkStrictly: true
};
const positionList = ref([]);

const visible = defineModel("visible");
const props = defineProps(["positionCode"]);
const emits = defineEmits(["close", "confirm"]);
const tagBorderColorList = {
  1: "#3B82F6", // 正常
  2: "#F59E0B", // 带病运行
  3: "#10B981", // 备机
  4: "#EF4444", // 故障
  5: "#909399" // 未上线
};

const tagBgColorList = {
  1: "#EFF6FF",
  2: "#FEF5E6",
  3: "#E8F8F3",
  4: "#FEECEC",
  5: "#F4F4F5"
};

const loading = ref(true);
const total = ref(0);
const systemCodes = ref([]);
const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};
const data = reactive<Record<string, any>>({
  eqpId: "",
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  selectIds: [], // 选中的数据
  equipTypeList: [], // 列表数据

  facList: [], // 厂区下拉框
  classNameList: [], // 科室下拉框
  systemList: [], // 系统下拉框
  categoryList: [], // 设备总称下拉框
  typeIdList: [], // 设备类型下拉框
  modelIdList: [] // 设备型号下拉框
});

const {
  equipTypeList,
  queryParams,
  selectIds,

  facList,
  classNameList,
  systemList,
  categoryList,
  typeIdList,
  modelIdList,
  eqpId
} = toRefs(data);
onMounted(async () => {
  // queryTable();
  queryClassNameSelect();
  positionList.value = (await getTableData({})) as [];
});
watch(
  () => visible.value,
  newVal => {
    if (newVal) {
      queryTable();
    }
  }
);
// 如果有厂区和科室，根据他们的值获取系统
const handleSystemFocus = async () => {
  systemList.value = await querySystemSelect({ factoryArea: queryParams.value.facCode, className: queryParams.value.className });
};

const handleSystemClear = () => {
  systemCodes.value = [];
};
// 如果有总称，根据他们的值获取类型
const handleTypeFocus = async () => {
  const typeData = await getEquipTypeSelect({ categoryId: queryParams.value.categoryId, systemCode: queryParams.value.systemCodes });
  typeIdList.value = typeData?.map(item => ({ label: item.name, value: item.id }));
};
// 如果有类型，根据他们的值获取型号
const handleModelFocus = async () => {
  const modelIdData = await getEquipModelSelect({ typeId: queryParams.value.typeId, categoryId: queryParams.value.categoryId });
  modelIdList.value = modelIdData?.map(item => ({ label: item.name, value: item.id }));
};
// 搜索项目下拉框
const queryClassNameSelect = async () => {
  facList.value = await queryDictData({ typeCode: "factoryArea" });
  classNameList.value = await queryCurrentClassList();
  categoryList.value = await getEquipNameSelect({});
};

// 改变厂区，清空系统
const handleChangeFac = () => {
  queryParams.value.systemCodes = "";
  systemCodes.value = [];
};
// 改变科室，清空系统
const handleChangeClass = () => {
  queryParams.value.systemCodes = "";
  systemCodes.value = [];
};
// 改变总称，清空类型和型号
const handleCategoryChange = () => {
  queryParams.value.typeId = "";
  queryParams.value.modelId = "";
};
// 改变类型，清空清号
const handleTypeChange = () => {
  queryParams.value.modelId = "";
};

// 点击左侧树节点，获取categoryId，查询设备列表
const nodeClick = (e1emData, nodeData) => {
  if (e1emData.type === "factoryArea") {
    // 一级工厂
    queryParams.value.facCode = e1emData.code;
    systemCodes.value = [];
  } else if (e1emData.type === "className") {
    // 二级科室
    queryParams.value.facCode = nodeData.parent.data.code;
    queryParams.value.className = e1emData.code;
    systemCodes.value = [];
  } else if (e1emData.type === "systemCategory") {
    const codes = [e1emData.code];
    if (e1emData.children && e1emData.children.length > 0) {
      e1emData.children.forEach(item => {
        codes.push(item.code);
      });
    }
    systemCodes.value = codes;
  }
  queryTable();
};

const queryTable = async () => {
  try {
    loading.value = true;
    const temp = JSON.parse(JSON.stringify(queryParams.value));
    delete temp.systemCodes;
    if (props.positionCode) {
      temp.positionCodes = [props.positionCode];
    }
    const res = await queryEquipLedger({ systemCodes: systemCodes.value, ...temp });
    equipTypeList.value = res?.data || [];
    total.value = res?.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  systemCodes.value = [];
  queryTable();
}

/** 多选框选中数据 */
const handleSelectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.eqpId) {
      selectIds.value.push(item.eqpId);
    }
  });
};

function closeDialog() {
  visible.value = false;
}
const confirm = async () => {
  emits("confirm", selectIds.value);
};
</script>
